<template>
  <div class="app-container bg">
    <div class="box-container">
      <div style="border-bottom: 1px solid #ddd; margin-bottom: 10px">
        <el-radio-group
          v-model="showType"
          @change="showTypeChange"
          style="gap: 40px"
        >
          <el-radio-button label="1">科室</el-radio-button>
          <el-radio-button label="2" style="border-left: 1px solid #dcdfe6"
            >学员</el-radio-button
          >
        </el-radio-group>
      </div>

      <div class="status-container mb15" style="font-size: 14px">
        <!-- 全部统计 -->
        <div
          class="status-item"
          :style="{
            color: tagIndex == 0 ? '#A52529' : '',
            'font-weight': tagIndex == 0 ? 'bolder' : '',
          }"
          @click="clickAll(0, null)"
        >
          全部：{{ registerBaseVo.total || 0 }}
        </div>

        <!-- 审批状态 -->
        <template v-if="isSystem">
          <div
            class="status-item"
            :style="{
              color: tagIndex == 3 ? '#A52529' : '',
              'font-weight': tagIndex == 3 ? 'bolder' : '',
            }"
            @click="clickAll(3, 2, '待审批')"
          >
            待审批：{{ registerBaseVo.auditStatus2 || 0 }}
          </div>
          <div
            class="status-item"
            :style="{
              color: tagIndex == 4 ? '#A52529' : '',
              'font-weight': tagIndex == 4 ? 'bolder' : '',
            }"
            @click="clickAll(4, 1, '转审中')"
          >
            转审中：{{ registerBaseVo.auditStatus1 || 0 }}
          </div>
        </template>

        <template v-else>
          <div
            class="status-item"
            :style="{
              color: tagIndex == 1 ? '#A52529' : '',
              'font-weight': tagIndex == 1 ? 'bolder' : '',
            }"
            @click="clickAll(1, 1, '待审批')"
          >
            待审批：{{ registerBaseVo.auditStatus1 || 0 }}
          </div>
          <div
            class="status-item"
            :style="{
              color: tagIndex == 2 ? '#A52529' : '',
              'font-weight': tagIndex == 2 ? 'bolder' : '',
            }"
            @click="clickAll(2, 2, '转审中')"
          >
            转审中：{{ registerBaseVo.auditStatus2 || 0 }}
          </div>
        </template>

        <!-- 审批结果 -->
        <div
          class="status-item"
          :style="{
            color: tagIndex == 5 ? '#A52529' : '',
            'font-weight': tagIndex == 5 ? 'bolder' : '',
          }"
          @click="clickAll(5, 3)"
        >
          审批通过：{{ registerBaseVo.auditStatus3 || 0 }}
        </div>
        <div
          class="status-item"
          :style="{
            color: tagIndex == 6 ? '#A52529' : '',
            'font-weight': tagIndex == 6 ? 'bolder' : '',
          }"
          @click="clickAll(6, 4)"
        >
          审批拒绝：{{ registerBaseVo.auditStatus4 || 0 }}
        </div>
        <div
          class="status-item"
          :style="{
            color: tagIndex == 7 ? '#A52529' : '',
            'font-weight': tagIndex == 7 ? 'bolder' : '',
          }"
          @click="clickAll(7, 5, '已退回')"
        >
          已退回：{{ registerBaseVo.auditStatus5 || 0 }}
        </div>

        <!-- 通知状态 -->
        <div
          class="status-item"
          :style="{
            color: tagIndex == 8 ? '#A52529' : '',
            'font-weight': tagIndex == 8 ? 'bolder' : '',
          }"
          @click="clickAll(8, 1, '待通知')"
        >
          待通知：{{ registerBaseVo.noticeStatus1 || 0 }}
        </div>
        <div
          class="status-item"
          :style="{
            color: tagIndex == 9 ? '#A52529' : '',
            'font-weight': tagIndex == 9 ? 'bolder' : '',
          }"
          @click="clickAll(9, 2, '待确认')"
        >
          待确认：{{ registerBaseVo.noticeStatus2 || 0 }}
        </div>
        <div
          class="status-item"
          :style="{
            color: tagIndex == 10 ? '#A52529' : '',
            'font-weight': tagIndex == 10 ? 'bolder' : '',
          }"
          @click="clickAll(10, 3, '已确认')"
        >
          已确认：{{ registerBaseVo.noticeStatus3 || 0 }}
        </div>
        <div
          class="status-item"
          :style="{
            color: tagIndex == 11 ? '#A52529' : '',
            'font-weight': tagIndex == 11 ? 'bolder' : '',
          }"
          @click="clickAll(11, 4)"
        >
          延期未确认：{{ registerBaseVo.noticeStatus4 || 0 }}
        </div>
        <div
          class="status-item"
          :style="{
            color: tagIndex == 12 ? '#A52529' : '',
            'font-weight': tagIndex == 12 ? 'bolder' : '',
          }"
          @click="clickAll(12, 5)"
        >
          已取消：{{ registerBaseVo.noticeStatus5 || 0 }}
        </div>

        <!-- 签字状态 -->
        <div
          class="status-item"
          :style="{
            color: tagIndex == 13 ? '#A52529' : '',
            'font-weight': tagIndex == 13 ? 'bolder' : '',
          }"
          @click="clickAll(13, 1)"
        >
          已签字：{{ registerBaseVo.signedStatus || 0 }}
        </div>
        <div
          class="status-item"
          :style="{
            color: tagIndex == 14 ? '#A52529' : '',
            'font-weight': tagIndex == 14 ? 'bolder' : '',
          }"
          @click="clickAll(14, 0)"
        >
          待签字：{{ registerBaseVo.noSignStatus || 0 }}
        </div>
        <div
          class="status-item"
          :style="{
            color: tagIndex == 15 ? '#A52529' : '',
            'font-weight': tagIndex == 15 ? 'bolder' : '',
          }"
          @click="clickAll(15, 1)"
        >
          学员未签字：{{ registerBaseVo.studentNoSign || 0 }}
        </div>

        <!-- 退款状态 -->
        <div
          class="status-item"
          :style="{
            color: tagIndex == 16 ? '#A52529' : '',
            'font-weight': tagIndex == 16 ? 'bolder' : '',
          }"
          @click="clickAll(16, 1)"
        >
          已退款：{{ registerBaseVo.payRefundStatus || 0 }}
        </div>
      </div>
      <el-form
        class="box-container"
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="100px"
      >
        <el-form-item label="" style="width: 160px" prop="registerDeptId">
          <el-select
            v-model="queryParams.registerDeptId"
            placeholder="请选择进修科目"
            filterable
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="(item, index) in registerDeptList"
              :key="index"
              :label="item.registerDeptName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label=""
          style="width: 160px"
          prop="registerTypeId"
          v-if="false"
        >
          <el-select
            v-model="queryParams.registerTypeId"
            placeholder="请选择招生类型"
            filterable
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="(item, index) in registerTypeList"
              :key="index"
              :label="item.registerTypeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="" style="width: 160px" prop="batchName">
          <el-select
            popper-class="custom-select"
            v-model="queryParams.batchName"
            placeholder="请选择招生批次"
            filterable
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="(item, index) in registerBatchList"
              :key="index"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="" style="width: 160px" prop="registerYear">
          <el-date-picker
            v-model="queryParams.registerYear"
            type="year"
            placeholder="请选择招生年份"
            style="width: 160px"
            format="yyyy"
            value-format="yyyy"
            @change="handleQuery"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label=""
          v-if="showType == 2"
          style="width: 160px"
          prop="userName"
        >
          <el-input
            v-model="queryParams.userName"
            placeholder="请输入姓名"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="" style="width: 160px" prop="sourceUnitType">
          <el-select
            v-model="queryParams.sourceUnitType"
            placeholder="选择生源单位类型"
            filterable
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="(item, index) in sourceUnitTypeList"
              :key="index"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label=""
          v-if="showType == 2"
          style="width: 160px"
          prop="durationName"
        >
          <el-select
            v-model="queryParams.durationName"
            placeholder="请选择进修时长"
            filterable
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="(item, index) in registerPeriodList"
              :key="index"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>

      <!-- <div v-if="showType == 1">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              class="buttonT"
              size="small"
              @click="noticeContentOpen"
              >修改通知书内容</el-button
            >
          </el-col>
        </el-row>
      </div> -->
      <el-row v-if="showType == 2" :gutter="10" class="mb8">
        <el-col
          :span="1.5"
          v-if="
            (isAdmin || isSystem || isManage || isSecretary) && !checkUserId
          "
        >
          <el-button
            type="primary"
            size="small"
            :disabled="multiple"
            @click="auditOpen"
            >批量审批</el-button
          >
        </el-col>
        <el-col :span="1.5" v-if="isAdmin || isSystem">
          <el-button
            type="primary"
            size="small"
            :disabled="multiple"
            v-hasPermi="['business:registerInfo:notice']"
            @click="noticeOpen"
            >批量通知</el-button
          >
        </el-col>
        <el-col :span="1.5" v-if="isAdmin || isSystem">
          <el-button
            type="primary"
            :disabled="multiple"
            size="small"
            class="buttonD"
            @click="handleDelete"
            >批量删除</el-button
          >
        </el-col>
        <el-col :span="1.5" v-if="isAdmin || isSystem">
          <el-button
            type="primary"
            size="small"
            :disabled="multiple"
            @click="sourceOpen"
            >设置生源类型</el-button
          >
        </el-col>
        <el-col :span="1.5" v-if="isAdmin || isSystem">
          <el-button
            type="primary"
            :disabled="multiple"
            size="small"
            @click="updateNoticeOpen"
            >修改通知状态</el-button
          >
        </el-col>
        <el-col
          :span="1.5"
          v-if="isAdmin || isSystem || isManage || isSecretary"
        >
          <el-button
            type="primary"
            size="small"
            v-hasPermi="['business:registerInfo:export']"
            @click="exportStudent"
            >导出学员</el-button
          >
        </el-col>
        <el-col :span="1.5" v-if="isAdmin || isSystem">
          <el-button
            type="primary"
            size="small"
            :disabled="tagIndex !== 5"
            @click="exportBadge"
            >导出工牌</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="small"
            @click="handleImport"
            v-if="isAdmin || isSystem"
            >导入学员信息</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="small"
            @click="handleAgent"
            v-if="isAdmin || isSystem"
            >代理报名</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="small"
            @click="downloadSignature"
            v-if="(isAdmin || isSystem) && tagIndex == 13"
            >下载文件</el-button
          >
        </el-col>
        <el-col :span="1" v-if="isManage && (tagIndex == 14 || tagIndex == 0)">
          <el-button
            type="primary"
            size="small"
            @click="handsign"
            :disabled="multiple"
            >批量签字</el-button
          >
        </el-col>
      </el-row>
    </div>

    <div class="box-container">
      <div v-if="showType == 1" class="custom-table">
        <div class="custom-dept" v-for="(row, index) in dataList" :key="index">
          <div class="colw title">{{ row.registerDeptName }}</div>
          <div class="colw flex">
            <div class="col">
              {{ row.auditStatusTotal || 0 }}
              <div class="desc">报名总数</div>
            </div>
            <div class="col" v-if="isSystem">
              <span class="red">{{ row.auditStatus2 }}</span> /
              {{ row.auditStatus1 }}
              <div class="desc">
                <span :class="namekey == '待审批' ? 'red' : ''">待审</span
                >/<span :class="namekey == '转审中' ? 'red' : 'red'">转审</span>
              </div>
            </div>
            <div class="col" v-else>
              <span class="red">{{ row.auditStatus1 }}</span> /
              {{ row.auditStatus2 }}
              <div class="desc">
                <span :class="namekey == '待审批' ? 'red' : ''">待审</span
                >/<span :class="namekey == '转审中' ? 'red' : ''">转审</span>
              </div>
            </div>
            <div class="col">
              <span class="red">{{ row.auditStatus5 }}</span>
              <div class="desc" :class="namekey == '已退回' ? 'red' : ''">
                已退回
              </div>
            </div>
            <div class="col">
              {{ row.noticeStatus1 }}
              <div class="desc" :class="namekey == '待通知' ? 'red' : ''">
                待通知
              </div>
            </div>
            <div class="col">
              {{ row.noticeStatus2 }}
              <div class="desc" :class="namekey == '待确认' ? 'red' : ''">
                待确认
              </div>
            </div>
            <div class="col">
              {{ row.noticeStatus3 }}
              <div class="desc" :class="namekey == '已确认' ? 'red' : ''">
                已确认
              </div>
            </div>
          </div>
          <div class="colw func" @click="viewOpen(row)">
            <el-button size="small" type="primary">查看名单</el-button>
          </div>
        </div>
      </div>
      <div v-if="showType == 2" class="custom-table">
        <el-checkbox
          v-model="AllCheck"
          @change="handleSelectionChangeAll"
          style="transform: scale(1.2); margin-bottom: 20px; margin-left: 20px"
          >全选</el-checkbox
        >
        <div
          class="custom-register-for"
          v-for="(row, index) in dataList"
          :key="index"
        >
          <div class="custom-register">
            <div class="col border" style="display: flex">
              <div style="margin-left: 15px; text-align: left; width: 100%">
                <div class="user-name">
                  <div style="margin-right: 10px">
                    <el-checkbox
                      v-model="row.check"
                      style="transform: scale(1.2)"
                      @change="handleSelectionChange($event, index)"
                    />
                  </div>
                  <span
                    style="
                      font-size: 18px;
                      font-weight: bolder;
                      color: #a52529;
                      cursor: pointer;
                    "
                    @click="detailOpen(row)"
                    >{{ row.userName }}</span
                  >
                  <el-tag
                    type="info"
                    size="small"
                    color="#fff"
                    style="
                      margin-left: 10px;
                      width: 75px;
                      color: #f5a623;
                      border: 1px solid #f5a623;
                    "
                    >第{{ row.labelSubmit }}次提交</el-tag
                  >
                  <el-tag
                    type="info"
                    size="small"
                    color="#fff"
                    style="
                      margin-left: 10px;
                      width: 75px;
                      color: #f5a623;
                      border: 1px solid #f5a623;
                    "
                    >第{{ row.labelEngage }}次进修</el-tag
                  >
                </div>
                <div class="info">
                  <div class="flexInfo">
                    <div>
                      进修科目：{{ row.registerDeptName }}
                      <i
                        class="el-icon-edit-outline systemColor"
                        v-hasPermi="['business:registerInfo:editdept']"
                        style="font-size: 15px; cursor: pointer"
                        @click="editF(row)"
                        v-if="
                          (row.auditStatusName == '审批通过' ||
                            row.auditStatus == 1 ||
                            row.auditStatus == 2) &&
                          row.noticeStatusName != '已取消' &&
                          row.noticeStatusName != '已确认'
                        "
                      ></i>
                    </div>
                    <div>
                      进修期限：{{ row.durationStartDate }} -
                      {{ row.durationEndDate
                      }}{{
                        getMonthDiff(row.durationStartDate, row.durationEndDate)
                      }}
                    </div>
                    <div>
                      申请单位：{{ row.unitHospitalName
                      }}<el-tag
                        style="margin-left: 10px"
                        type="success"
                        size="mini"
                        v-if="row.sourceUnitType"
                        >{{ row.sourceUnitType }}</el-tag
                      >
                    </div>
                    <div>手机号：{{ row.phoneNumber }}</div>
                  </div>
                  <div class="flexInfo">
                    <div>
                      进修费用：<span
                        :class="getStatusTag(row).className"
                        class="payment-status"
                      >
                        {{ getStatusTag(row).text }}
                      </span>
                    </div>
                    <div>
                      培训视频：{{ row.progress == 100 ? "已完成" : "/" }}
                    </div>
                    <div>
                      告知书/承诺书：<span
                        style="cursor: pointer"
                        @click.stop="signatureOpen(row)"
                        v-html="signature(row)"
                      ></span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col border">
              <img
                src="../../../../assets/images/biezhen.png"
                @click="getInfo(row)"
                style="width: 40px; height: 40px"
              />
              <el-button size="mini" type="text" @click="getInfo(row)"
                >申报材料
              </el-button>
              <el-button size="mini" type="text" @click="getInfo(row)">
                {{ row.show ? "收起" : "展开" }}
              </el-button>
            </div>
            <div class="col border">
              <div class="desc">审批状态</div>

              <div v-if="row.auditStatus == 1" class="systemColor">
                科室待审批
              </div>
              <div v-else-if="row.auditStatus == 2" class="systemColor">
                管理员待审批
              </div>
              <div v-else-if="row.payStatus == 3" class="systemColor">
                已退款
              </div>
              <div v-else class="systemColor">
                {{ row.auditStatusName }}
              </div>
            </div>

            <div class="col border">
              <i
                class="el-icon-document-copy systemColor"
                @click="auditLogOpen(row)"
                style="font-size: 30px"
              ></i>
              <!-- 审批历史按钮 -->
              <el-button size="mini" type="text" @click="auditLogOpen(row)">
                审批历史
              </el-button>
            </div>

            <div class="col border" style="position: relative">
              <!-- 审批 -->
              <el-button
                size="mini"
                type="text"
                v-if="
                  (row.auditStatus == 1 || row.auditStatus == 2) && !checkUserId
                "
                icon="el-icon-edit"
                @click="handleAudit(row)"
                >审批
              </el-button>
              <el-tag
                type="info"
                v-if="row.noticeStatus == 4"
                size="small"
                color="#fff"
                style="
                  margin-left: 10px;
                  width: 75px;
                  color: #f5a623;
                  border: 1px solid #f5a623;
                "
                >延期未确认</el-tag
              >
              <!-- 通知书按钮 -->
              <el-button
                size="mini"
                type="text"
                icon="el-icon-notebook-2"
                @click="bookOpen(row, 'view')"
                style="z-index: 2"
                v-if="row.noticeStatus > 1"
              >
                已发送的通知书
              </el-button>

              <!-- 图片，条件满足时显示 -->
              <img
                src="../../../../assets/images/true.png"
                style="
                  width: 80px;
                  height: 80px;
                  position: absolute;
                  bottom: 0;
                  right: 0;
                  z-index: 1;
                "
                v-if="row.noticeStatusName == '已确认'"
                alt=""
              />
              <img
                src="../../../../assets/images/confiCancel.png"
                style="
                  width: 80px;
                  height: 80px;
                  position: absolute;
                  bottom: 0;
                  right: 0;
                  z-index: 1;
                "
                v-if="row.noticeStatusName == '已取消'"
                alt=""
              />
            </div>
          </div>
          <div v-if="row.show" class="custom-register-detail">
            <div class="main-container-detail">
              <div class="header-titles">
                <el-button
                  v-for="(category, index) in imageData"
                  :key="index"
                  @click="toggleCategoryVisibility(index)"
                  :class="{ active: category.visible }"
                >
                  {{ category.title }}
                </el-button>
              </div>
              <div>
                <div
                  class="image-box"
                  v-for="(category, index) in visibleImageCategories"
                  :key="index"
                >
                  <div
                    v-for="(image, imgIndex) in category.images"
                    :key="imgIndex"
                    class="image-with-download"
                  >
                    <el-image
                      class="image-container"
                      lazy
                      :src="baseURL + image"
                      :initial-index="index"
                      :preview-src-list="preview_src_list"
                    />
                    <el-button
                      class="download-button"
                      type="text"
                      @click="downloadImage(baseURL + image)"
                    >
                      下载
                    </el-button>
                  </div>
                </div>
              </div>

              <div class="download-all">
                <el-button type="text" @click="downloadAllImages"
                  >下载全部</el-button
                >
              </div>
            </div>
          </div>
        </div>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <el-dialog
      title="修改进修科目"
      :visible.sync="editShow"
      width="700px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="editForm" :model="editForm" :rules="editRules">
        <el-form-item label="请选择进修科目" style="width: 160px" prop="id">
          <el-select
            v-model="editForm.registerDeptId"
            placeholder="请选择进修科目"
            filterable
            clearable
            @change="handleQueryEdit"
          >
            <el-option
              v-for="(item, index) in registerDeptList"
              :key="index"
              :label="item.registerDeptName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editFormSubmit">确 定</el-button>
        <el-button @click="editShow = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="审批"
      :visible.sync="auditShow"
      width="700px"
      append-to-body
      :close-on-click-modal="false"
    >
      <div style="display: flex; flex-direction: column; margin-bottom: 30px">
        <span>请选择审批意见：</span>
        <div
          style="
            display: flex;
            align-items: center;
            margin-top: 20px;
            margin-left: 65px;
          "
        >
          <el-button
            type="success"
            :class="{ 'is-active1': auditForm.auditStatus == 1 }"
            @click="auditForm.auditStatus = 1"
            plain
            >同意</el-button
          >
          <el-button
            type="warning"
            :class="{ 'is-active2': auditForm.auditStatus == 2 }"
            @click="auditForm.auditStatus = 2"
            plain
            >退回</el-button
          >
          <el-button
            type="danger"
            :class="{ 'is-active3': auditForm.auditStatus == 3 }"
            @click="auditForm.auditStatus = 3"
            plain
            >拒绝</el-button
          >
        </div>
      </div>
      <el-form
        ref="auditForm"
        :model="auditForm"
        :rules="auditRules"
        v-if="auditForm.auditStatus != 1"
        label-width="80px"
      >
        <el-form-item label="审批意见" :required="false" prop="remark">
          <el-input
            type="textarea"
            :rows="5"
            v-model="auditForm.remark"
            placeholder="请输入审批意见"
          />
          <auditTemplateList @change="auditRemarkChange" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="auditFormSubmit()">确定</el-button>
        <el-button @click="auditShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="录取通知"
      :visible.sync="noticeShow"
      width="900px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="noticeForm"
        :model="noticeForm"
        :rules="noticeRules"
        label-width="120px"
      >
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="进修开始时间" prop="startDate">
              <el-date-picker
                v-model="noticeForm.startDate"
                style="width: 100%"
                type="date"
                placeholder="请选择进修开始时间"
                value-format="yyyy/MM/dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进修结束时间" prop="endDate">
              <el-date-picker
                v-model="noticeForm.endDate"
                style="width: 100%"
                type="date"
                placeholder="请选择进修结束时间"
                value-format="yyyy/MM/dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报到日期" prop="registerDate">
              <el-date-picker
                v-model="noticeForm.registerDate"
                style="width: 100%"
                type="date"
                @change="registerDateChange"
                placeholder="请选择报到日期"
                value-format="yyyy/MM/dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报到时间" prop="registerTime">
              <el-time-select
                placeholder="开始时间"
                v-model="noticeForm.registerTimeStart"
                :picker-options="{
                  start: '08:00',
                  step: '00:30',
                  end: '18:30',
                }"
                @change="registerTimeChange"
                style="width: 140px"
              >
              </el-time-select>
              至
              <el-time-select
                placeholder="结束时间"
                v-model="noticeForm.registerTimeEnd"
                :picker-options="{
                  start: '08:00',
                  step: '00:30',
                  end: '18:30',
                  minTime: noticeForm.registerTimeStart,
                }"
                @change="registerTimeChange"
                style="width: 140px"
              >
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报到地点" prop="registerAddress">
              <el-input
                v-model="noticeForm.registerAddress"
                placeholder="请输入报到地点"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进修费(元)" prop="engageMoney">
              <el-input
                type="number"
                v-model.number="noticeForm.engageMoney"
                placeholder="请输入进修费(元)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实验材料费(元)" prop="materialMoney">
              <el-input
                type="number"
                v-model.number="noticeForm.materialMoney"
                placeholder="请输入实验材料费(元)"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="开户行" prop="bankName">
              <el-input
                v-model="noticeForm.bankName"
                placeholder="请输入开户行"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行卡号" prop="bankCardNumber">
              <el-input
                v-model="noticeForm.bankCardNumber"
                placeholder="请输入银行卡号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="财务账号" prop="financialAccount">
              <el-input
                v-model="noticeForm.financialAccount"
                placeholder="请输入财务账号"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactMan">
              <el-input
                v-model="noticeForm.contactMan"
                placeholder="请输入联系人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input
                v-model="noticeForm.contactPhone"
                placeholder="请输入联系电话"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="传真" prop="fax">
              <el-input v-model="noticeForm.fax" placeholder="请输入传真" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="noticeForm.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="通知书内容" prop="noticeContent">
              <editor v-model="noticeForm.noticeContent" :min-height="400" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="bookPreviewOpen">预 览</el-button>
        <el-button type="primary" @click="noticeFormSubmit">确 定</el-button>
        <el-button @click="noticeShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="设置生源类型"
      :visible.sync="sourceShow"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form label-width="120px">
        <el-form-item label="生源单位类型">
          <el-radio-group v-model="sourceUnitType" size="small">
            <el-radio
              v-for="(item, index) in sourceUnitTypeList"
              :key="index"
              :label="item.name"
              >{{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sourceFormSubmit">确 定</el-button>
        <el-button @click="sourceShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="修改通知状态"
      :visible.sync="updateNoticeShow"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form label-width="120px">
        <el-form-item label="通知状态">
          <el-radio-group v-model="updateNoticeValue" size="small">
            <el-radio :label="2">待确认</el-radio>
            <el-radio :label="3">已确认</el-radio>
            <el-radio :label="5">已取消</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateNoticeFormSubmit"
          >确 定</el-button
        >
        <el-button @click="updateNoticeShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="审批历史"
      :visible.sync="auditLogShow"
      width="900px"
      append-to-body
      :close-on-click-modal="false"
    >
      <auditLogList v-if="auditLogShow" :register-id="registerInfo.id" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditLogShow = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="报名详情"
      :visible.sync="detailShow"
      width="1040px"
      append-to-body
      :close-on-click-modal="false"
    >
      <!-- <registerInfoDetail v-if="detailShow" :register-id="registerInfo.id" :step-active="'3'" /> -->
      <registerInfoDetailInfo
        v-if="detailShow"
        :register-id="registerInfo.id"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailShow = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="修改通知书内容"
      :visible.sync="noticeContentShow"
      width="1040px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="noticeContentForm"
        :model="noticeContentForm"
        :rules="noticeRules"
        label-width="120px"
      >
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="进修开始时间" prop="startDate">
              <el-date-picker
                v-model="noticeContentForm.startDate"
                style="width: 100%"
                type="date"
                placeholder="请选择进修开始时间"
                value-format="yyyy/MM/dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进修结束时间" prop="endDate">
              <el-date-picker
                v-model="noticeContentForm.endDate"
                style="width: 100%"
                type="date"
                placeholder="请选择进修结束时间"
                value-format="yyyy/MM/dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报到日期" prop="registerDate">
              <el-date-picker
                v-model="noticeContentForm.registerDate"
                style="width: 100%"
                type="date"
                placeholder="请选择报到日期"
                value-format="yyyy/MM/dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报到时间" prop="registerTime">
              <el-time-select
                placeholder="开始时间"
                v-model="noticeContentForm.registerTimeStart"
                :picker-options="{
                  start: '08:00',
                  step: '00:30',
                  end: '18:30',
                }"
                @change="registerTimeChange"
                style="width: 140px"
              >
              </el-time-select>
              至
              <el-time-select
                placeholder="结束时间"
                v-model="noticeContentForm.registerTimeEnd"
                :picker-options="{
                  start: '08:00',
                  step: '00:30',
                  end: '18:30',
                  minTime: noticeContentForm.registerTimeStart,
                }"
                @change="registerTimeChange"
                style="width: 140px"
              >
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报到地点" prop="registerAddress">
              <el-input
                v-model="noticeContentForm.registerAddress"
                placeholder="请输入报到地点"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进修费(元)" prop="engageMoney">
              <el-input
                type="number"
                v-model.number="noticeContentForm.engageMoney"
                placeholder="请输入进修费(元)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实验材料费(元)" prop="materialMoney">
              <el-input
                type="number"
                v-model.number="noticeContentForm.materialMoney"
                placeholder="请输入实验材料费(元)"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="开户行" prop="bankName">
              <el-input
                v-model="noticeContentForm.bankName"
                placeholder="请输入开户行"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行卡号" prop="bankCardNumber">
              <el-input
                v-model="noticeContentForm.bankCardNumber"
                placeholder="请输入银行卡号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="财务账号" prop="financialAccount">
              <el-input
                v-model="noticeContentForm.financialAccount"
                placeholder="请输入财务账号"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactMan">
              <el-input
                v-model="noticeContentForm.contactMan"
                placeholder="请输入联系人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input
                v-model="noticeContentForm.contactPhone"
                placeholder="请输入联系电话"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="传真" prop="fax">
              <el-input
                v-model="noticeContentForm.fax"
                placeholder="请输入传真"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="noticeContentForm.remark"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="通知书内容" prop="noticeContent">
              <editor
                v-model="noticeContentForm.noticeContent"
                :min-height="400"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="noticeContentShow = false">关 闭</el-button>
        <el-button type="primary" @click="openNoticeContent(noticeContentForm)"
          >预 览</el-button
        >
        <el-button type="primary" @click="saveNoticeContent">保 存</el-button>
      </div>
    </el-dialog>
    <!-- 仅预览编辑后的内容 -->
    <el-dialog
      title="预览通知书内容"
      :visible.sync="noticePreviewShow"
      width="1040px"
      append-to-body
      :close-on-click-modal="false"
    >
      <div
        class="enter-container"
        v-html="noticeContentForm.noticeContent"
      ></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="noticePreviewShow = false">关 闭</el-button>
      </div>
    </el-dialog>
    <!-- 批量签字弹窗 -->
    <el-dialog
      title="批量签字"
      :center="true"
      :visible.sync="signShow"
      width="300px"
      append-to-body
      :close-on-click-modal="false"
      @close="closeSignDialog"
    >
      <div class="body" v-if="!signShowT">
        <span
          >{{ nickName }}老师您好，确定给所选的
          {{ ids.length }} 位学员，签署行风自律书文件吗？</span
        >
        <div style="margin-top: 20px; display: flex; flex-direction: column">
          <div style="display: flex; z-index: 2">
            <div>签名样式：</div>
            <i
              class="el-icon-edit"
              v-if="mySignQR"
              style="margin-left: 120px; font-size: 20px; cursor: pointer"
              @click="handleEditSign"
            ></i>
          </div>
          <div
            style="
              z-index: 1;
              text-align: center;
              display: flex;
              flex-direction: column;
              align-items: center;
              margin-top: -25px;
            "
          >
            <img :src="mySignQR" style="width: 90px" v-if="mySignQR" alt="" />
            <img
              :src="signImg"
              style="width: 90px"
              v-if="showSignImg && !mySignQR"
              alt=""
            />
            <span
              class="systemColor"
              v-if="gq"
              @click="refreshSign"
              style="margin-top: 20px; display: flex; align-items: center"
              >已过期,刷新<i
                class="el-icon-refresh-right"
                style="margin-left: 10px; font-size: 18px; cursor: pointer"
              ></i
            ></span>
            <span
              class="systemColor"
              v-if="showSignImg && !mySignQR"
              style="margin-top: 20px"
              >微信扫码预设签名样式<i
                class="el-icon-refresh-right"
                @click="getCodeSign"
                style="margin-left: 10px; font-size: 18px; cursor: pointer"
              ></i
            ></span>
          </div>
        </div>
      </div>
      <div class="body" v-else>
        <p style="text-align: center">已签署成功</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeSignDialog" v-if="!signShowT">取 消</el-button>
        <el-button
          type="primary"
          @click="signSubmit"
          v-if="!signShowT"
          :disabled="!mySignQR"
          >确 认</el-button
        >
        <el-button type="primary" v-if="signShowT" @click="closeSignDialog"
          >确 认</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="查看通知书"
      :visible.sync="bookShow"
      width="900px"
      append-to-body
      :close-on-click-modal="false"
    >
      <registerBook
        :register-id="registerInfo.id"
        v-if="bookShow"
      ></registerBook>

      <div slot="footer" class="dialog-footer">
        <el-button @click="bookShow = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="预览修改通知书"
      :visible.sync="bookPreviewEditShow"
      width="940px"
      append-to-body
      :close-on-click-modal="false"
    >
      <RegisterBookPreviewEdit
        :form-obj="bookPreviewFormEdit"
        v-if="bookPreviewEditShow"
      ></RegisterBookPreviewEdit>
      <div slot="footer" class="dialog-footer">
        <el-button @click="bookPreviewEditShow = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="预览通知书"
      :visible.sync="bookPreviewShow"
      width="940px"
      append-to-body
      :close-on-click-modal="false"
    >
      <registerBookPreview
        :form-obj="bookPreviewForm"
        v-if="bookPreviewShow"
      ></registerBookPreview>
      <div slot="footer" class="dialog-footer">
        <el-button @click="bookPreviewShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip" v-if="false">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { consts } from "@/api/business/consts";
import {
  checkSureStatus,
  queryByCountRegisterBase,
  queryByDeptRegisterBase,
  saveAuditRegisterBase,
  saveNoticeRegisterBase,
  saveSourceRegisterBase,
  updateNoticeRegisterBase,
} from "@/api/business/registerBase";
import { listAllRegisterDept } from "@/api/business/registerDept";
import { getRegisterNeed } from "@/api/business/registerNeed";
import { mapGetters } from "vuex";

import {
  addKXBatchSign,
  delRegisterInfo,
  getKSBatchQRCode,
  getRegisterInfo,
  getSignedBook,
  listRegisterInfo,
  updateRegisterInfo,
} from "@/api/business/registerInfo";

import { setupBatchData } from "@/utils/batchUtils";

import { listAllRegisterType } from "@/api/business/registerType";
import { getSureInfo, updateSureInfo } from "@/api/business/sureInfo";
import { getMonthDiff } from "@/utils/dateUtils";
import { getToken } from "../../../../utils/auth";
import auditLogList from "./components/auditLogList";
import auditTemplateList from "./components/auditTemplateList";
import registerBook from "./components/registerBook";
import registerBookPreview from "./components/registerBookPreview";
import RegisterBookPreviewEdit from "./components/registerBookPreviewEdit";
import registerInfoDetail from "./components/registerInfoDetail";
import registerInfoDetailInfo from "./components/registerInfoDetailInfo";
let timer;

export default {
  name: "audit",
  components: {
    auditTemplateList,
    auditLogList,
    registerInfoDetail,
    registerBook,
    registerBookPreview,
    registerInfoDetailInfo,
    RegisterBookPreviewEdit,
  },
  data() {
    return {
      isSigning: false, // Flag to prevent multiple clicks
      signIntervalId: null, // To store the interval ID for QR code polling
      namekey: "",
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      ws: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      signShowT: false, //签字是否成功
      gq: false, //是否过期
      // 总条数
      total: 0,
      // 招生信息表格数据
      dataList: [],
      //全选
      AllCheck: false,
      //进修期限
      registerPeriodList: [
        { name: "所有进修时长", value: "" },
        { name: "1个月", value: "1个月" },
        { name: "3个月", value: "3个月" },
        { name: "6个月", value: "6个月" },
        { name: "12个月", value: "12个月" },
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        auditStatusList: [1, 2, 3, 4, 5],
        registerDeptId: null,
        registerTypeId: null,
        batchName: null,
        registerYear: null,
        userName: null,
        sourceUnitType: null,
        auditStatus: null,
        noticeStatus: null,
        durationName: null,
      },
      registerDeptList: [],
      registerTypeList: [],
      registerBatchList: [],
      registerBaseVo: {},
      // 页面显示
      showType: 1,
      // 批次数据
      batchDateList: [],
      // 批量审批
      auditShow: false,
      //修改进修科目
      editShow: false,
      editRules: {
        id: [{ required: true, message: "进修科目不能为空", trigger: "blur" }],
      },
      editForm: {
        id: "",
      },
      imageData: {}, //列表图片数据
      auditForm: {},
      auditRules: {
        auditStatus: [
          { required: true, message: "审批状态不能为空", trigger: "blur" },
        ],
        remark: [
          { required: false, message: "审批意见不能为空", trigger: "blur" },
        ],
      },
      // 批量通知
      noticeShow: false,
      noticeForm: {},
      noticeRules: {
        startDate: [
          { required: true, message: "进修开始时间不能为空", trigger: "blur" },
        ],
        endDate: [
          { required: true, message: "进修结束时间不能为空", trigger: "blur" },
        ],
        registerDate: [
          { required: true, message: "报到日期不能为空", trigger: "blur" },
        ],
        registerTime: [
          {
            required: true,
            message: "请选择报到开始时间、结束时间",
            trigger: "blur",
          },
        ],
        registerAddress: [
          { required: true, message: "报到地点不能为空", trigger: "blur" },
        ],
        engageMoney: [
          { required: true, message: "进修费(元)不能为空", trigger: "blur" },
        ],
        materialMoney: [
          {
            required: true,
            message: "实验材料费(元)不能为空",
            trigger: "blur",
          },
        ],
        bankName: [
          { required: true, message: "开户行不能为空", trigger: "blur" },
        ],
        bankCardNumber: [
          { required: true, message: "银行卡号不能为空", trigger: "blur" },
        ],
        financialAccount: [
          { required: true, message: "财务账号不能为空", trigger: "blur" },
        ],
        contactMan: [
          { required: true, message: "联系人不能为空", trigger: "blur" },
        ],
        contactPhone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
        ],
        fax: [{ required: true, message: "传真不能为空", trigger: "blur" }],
        remark: [{ required: true, message: "备注不能为空", trigger: "blur" }],
      },
      // 设置生源类型
      sourceShow: false,
      sourceUnitType: null,
      sourceUnitTypeList: consts.sourceUnitTypeList,
      // 修改通知状态
      updateNoticeShow: false,
      updateNoticeValue: null,
      registerInfo: {
        id: null,
      },
      // 审批历史
      auditLogShow: false,
      // 申报材料
      detailShow: false,
      // 修改通知书内容
      noticeContentShow: false,
      noticeContentForm: {},
      noticePreviewShow: false,
      // 角色判断
      isAdmin: false,
      isManage: false,
      isSystem: false,
      isSecretary: false,
      isTeacher: false,
      tagIndex: 0,
      bookPreviewFormEdit: {},
      bookPreviewEditShow: false,
      // 通知书
      bookShow: false,
      // 签字
      signShow: false,
      //签字图片
      signImg: "",
      expireUuid: "",
      // 预设签名
      mySignQR: "",
      // 是否显示签名图片
      showSignImg: false,
      // 批量通知-通知书预览
      bookPreviewShow: false,
      bookPreviewForm: {},
      webTargetUrl: "",
      // 导入学员信息
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API +
          "/business/registerBase/importRegister",
      },
    };
  },
  computed: {
    ...mapGetters(["name", "nickName"]),
    /**
     * 获取预览图片列表
     * @returns {string[]} 图片URL列表
     */
    preview_src_list() {
      return this.imageData.flatMap((category) =>
        category.images.map((image) => this.baseURL + image)
      );
    },
    /**
     * 获取可见的图片分类列表
     * @returns {Array} 过滤后的可见图片分类
     */
    visibleImageCategories() {
      return this.imageData.filter(
        (category) => category.visible && category.images.length > 0
      );
    },
    /**
     * 检查当前用户是否在黑名单中
     * @returns {boolean} 是否在黑名单中
     */
    checkUserId() {
      const userId = this.$store.getters.userId;
      const blackList = [2234, 1825, 2175, 1256, 1813, 1817, 1814, 1815];
      return blackList.includes(userId);
    },
  },
  async created() {
    this.isAdmin = this.$store.getters.roles.indexOf("admin") > -1;
    this.isManage = this.$store.getters.roles.indexOf("manage") > -1;
    this.isSystem = this.$store.getters.roles.indexOf("system") > -1;
    this.isSecretary = this.$store.getters.roles.indexOf("secretary") > -1;
    this.isTeacher = this.$store.getters.roles.indexOf("teacher") > -1;
    await this.getbatch();
    this.initData();
    this.listAllRegisterDept();
    this.listAllRegisterType();
  },
  methods: {
    // 获取批次数据
    async getbatch() {
      await setupBatchData(this);
    },
    signatureOpen(row) {
      console.log(row);
      getSignedBook(row.id).then((response) => {
        if (response.code === 200) {
          let url = [];
          response.data.forEach((item) => {
            url.push({
              url: this.baseURL + item.signPdfFile,
            });
          });
          url.forEach((item) => {
            //下载每一个文件
            fetch(item.url)
              .then((response) => response.blob())
              .then((blob) => {
                const url = URL.createObjectURL(blob);
                const a = document.createElement("a");
                a.href = url;
                a.download = item.url.split("/").pop();
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url); // 清理 URL 对象
              });
          });
        }
      });
    },
    signature(row) {
      let signCount = 0;
      let directorSigned = false;
      if (row.registerFlowList) {
        row.registerFlowList.forEach((item) => {
          if (item.nodeName === "签署进修生告知书" && item.nodeStatus === 1) {
            signCount += 1;
          }
          if (
            item.nodeName === "签署临床医务人员行风自律承诺书" &&
            item.nodeStatus === 1
          ) {
            signCount += 1;
          }
          if (
            item.nodeName === "科主任签署行风承诺书" &&
            item.nodeStatus === 1
          ) {
            directorSigned = true;
          }
        });
      }
      row.signCount = signCount;
      if (signCount === 0) {
        return "<span>/</span>";
      } else if (signCount === 1) {
        return "<span class='systemColor'>已完成（1/2）</span>";
      } else if (signCount === 2 && directorSigned) {
        return "<span class='systemColor'>已完成（2/2）</span>";
      } else if (signCount === 2 && !directorSigned) {
        return "<span class='systemColor'>已完成（1/2）</span>";
      }
    },
    registerDateChange(e) {
      console.log(e);
      let date = new Date(e);
      if (date < new Date()) {
        this.$modal.msgError("报到日期不能小于当前时间。");
        this.noticeForm.registerDate = "";
      }
    },
    toggleCategoryVisibility(index) {
      this.imageData.forEach((item, itemIndex) => {
        if (itemIndex === index) {
          item.visible = !item.visible;
        } else {
          item.visible = false;
        }
      });
    },
    downloadAllImages() {
      this.imageData.forEach((category) => {
        category.images.forEach((image) => {
          this.downloadImage(this.baseURL + image);
        });
      });
    },
    getStatusTag(row) {
      // 从registerFlowList中查找支付进修费用节点
      const paymentNode =
        row.registerFlowList &&
        row.registerFlowList.find((item) => item.nodeName === "支付进修费用");

      if (paymentNode) {
        // 优先检查退款状态
        if (paymentNode.refundStatus != null) {
          switch (paymentNode.refundStatus) {
            case 0:
              if (
                row.registerApprovalFlow &&
                row.registerApprovalFlow.approverRole === "admin"
              ) {
                return {
                  text: "退款待管理员审核",
                  className: "refunding",
                };
              } else if (
                row.registerApprovalFlow &&
                row.registerApprovalFlow.approverRole &&
                ["manage", "secretary"].some((role) =>
                  row.registerApprovalFlow.approverRole
                    .split(",")
                    .includes(role)
                )
              ) {
                return {
                  text: "退款待科室审核",
                  className: "refunding",
                };
              } else {
                return { text: "退款待审核", className: "refunding" };
              }
            case 1:
              if (
                row.registerApprovalFlow &&
                row.registerApprovalFlow.approverRole === "admin"
              ) {
                return {
                  text: "退款待管理员审核",
                  className: "refunding",
                };
              } else {
                return {
                  text: "退款审核中",
                  className: "refunding",
                };
              }
            case 2:
              return { text: "退款已审核", className: "refunding" };
            case 3:
              return { text: "退款已拒绝", className: "refunding" };
            case 4:
              return { text: "退款执行中", className: "refunding" };
            case 5:
              return { text: "已退款", className: "refunded" };
            case 6:
              return { text: "已失败", className: "failed" };
            default:
              return { text: "未知退款状态", className: "default" };
          }
        } else if (paymentNode.nodeStatus != null) {
          // 检查支付状态
          switch (paymentNode.nodeStatus) {
            case 0:
              return { text: "待支付", className: "unknown" };
            case 1:
              return { text: "已支付", className: "paid" };
            case 2:
              return { text: "支付失败", className: "failed" };
            case 3:
              return { text: "已逾期", className: "closed" };
            case 4:
              return { text: "退款中", className: "refunding" };
            case 5:
              return { text: "已退款", className: "refunded" };
            default:
              return { text: "查看详情", className: "default" };
          }
        }
      }

      return { text: "/", className: "default" };
    },
    downloadImage(imageUrl) {
      fetch(imageUrl)
        .then((response) => response.blob())
        .then((blob) => {
          const url = URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.href = url;
          a.download = imageUrl.split("/").pop();
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          URL.revokeObjectURL(url); // 清理 URL 对象
        });
    },
    //后面日期和前面日期相差月数日期格式 date1和date2 2024/12
    getMonthDiff(startDate, endDate) {
      return getMonthDiff(startDate, endDate);
    },

    getInfo(row) {
      console.log(row.show);
      if (row.show) {
        row.show = false;
        return;
      }
      this.dataList.forEach((item) => {
        item.show = false;
      });
      getRegisterInfo(row.id).then((response) => {
        row.show = true;
        const form = response.data; // 假设 response.data 就是 form 对象
        this.imageData = [
          {
            title: "进修申请表",
            field: "registerApplicationForm",
            images: form.registerApplicationForm
              ? form.registerApplicationForm.split(",")
              : [],
            visible: true,
          },
          {
            title: "毕业证书",
            field: "diploma",
            images: form.diploma ? form.diploma.split(",") : [],
            visible: false,
          },
          {
            title: "医疗机构等级图片",
            field: "medicalInstitutionLevel",
            images: form.medicalInstitutionLevel
              ? form.medicalInstitutionLevel.split(",")
              : [],
            visible: false,
          },
          {
            title: "资格证书",
            field: "qualification",
            images: form.qualification ? form.qualification.split(",") : [],
            visible: false,
          },
          {
            title: "执业证书",
            field: "practicingCertificate",
            images: form.practicingCertificate
              ? form.practicingCertificate.split(",")
              : [],
            visible: false,
          },
          {
            title: "执业注册信息查询结果",
            field: "practiceResult",
            images: form.practiceResult ? form.practiceResult.split(",") : [],
            visible: false,
          },
          {
            title: "职称证书",
            field: "professionalTitleCertificate",
            images: form.professionalTitleCertificate
              ? form.professionalTitleCertificate.split(",")
              : [],
            visible: false,
          },
          {
            title: "身份证",
            field: ["idCardFront", "idCardBack"],
            images: [
              ...(form.idCardFront ? form.idCardFront.split(",") : []),
              ...(form.idCardBack ? form.idCardBack.split(",") : []),
            ],
            visible: false,
          },
          {
            title: "电子证件照",
            field: "electronicIdPhoto",
            images: form.electronicIdPhoto
              ? form.electronicIdPhoto.split(",")
              : [],
            visible: false,
          },
          {
            title: "其他补充附件",
            field: "otherAttachment",
            images: form.otherAttachment ? form.otherAttachment.split(",") : [],
            visible: false,
          },
        ];
        console.log(this.imageData);
      });
    },
    initData() {
      this.getCount();
      this.getList();
    },
    clickAll(index, value, namekey) {
      console.log(namekey);
      this.canselAllcheck();

      this.tagIndex = index;
      if (index == 0) {
        this.queryParams.auditStatus = null;
        this.queryParams.noticeStatus = null;
      } else if (index >= 1 && index <= 7) {
        this.queryParams.auditStatus = value;
      } else if (index >= 8 && index <= 12) {
        this.queryParams.noticeStatus = value;
      } else if (index == 15) {
        this.queryParams.studentNoSign = value;
      } else if (index == 16) {
        this.queryParams.payStatus = 3;
      } else {
        this.queryParams.signStatus = value;
      }
      this.namekey = namekey;
      this.getList();
    },
    listAllRegisterDept() {
      listAllRegisterDept().then((response) => {
        this.registerDeptList.push({
          registerDeptName: "所有",
          id: "",
        });
        response.data.forEach((element) => {
          let data = {
            registerDeptName: element.registerDeptName,
            id: element.id,
          };
          this.registerDeptList.push(data);
        });
      });
    },
    listAllRegisterType() {
      listAllRegisterType().then((response) => {
        this.registerTypeList = response.data;
      });
    },
    getCount() {
      this.registerBaseVo = {};
      queryByCountRegisterBase().then((response) => {
        if (response.data) {
          this.registerBaseVo = response.data;
          this.registerBaseVo.total =
            this.registerBaseVo.auditStatus1 +
            this.registerBaseVo.auditStatus2 +
            this.registerBaseVo.auditStatus3 +
            this.registerBaseVo.auditStatus4 +
            this.registerBaseVo.auditStatus5;
        }
      });
    },
    getList() {
      this.loading = true;
      if (this.showType == 1) {
        this.dataList = [];
        queryByDeptRegisterBase(this.queryParams).then((response) => {
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      } else if (this.showType == 2) {
        this.dataList = [];
        listRegisterInfo(this.queryParams).then((response) => {
          //给this.dataList里面的每个对象添加一个show属性 false

          for (let i = 0; i < response.rows.length; i++) {
            response.rows[i].show = false;
          }
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }
    },
    //单独审批
    handleAudit(row) {
      this.auditForm = {
        registerIdList: [row.id],
        auditStatus: 1,
        remark: null,
      };
      this.auditShow = true;
    },
    // 批量审批
    auditOpen() {
      let list = this.dataList.filter((e) => this.ids.indexOf(e.id) > -1);
      for (let i = 0; i < list.length; i++) {
        console.log(list[i]);

        if (this.isManage && list[i].auditLevel != 0) {
          this.$modal.msgError("科室负责人请选择待审核数据");
          return;
        }
      }
      this.auditForm = {
        registerIdList: this.ids,
        auditStatus: 1,
        remark: null,
      };
      this.auditShow = true;
    },
    auditRemarkChange(e) {
      this.auditForm.remark = e;
    },
    auditFormSubmit() {
      if (this.auditForm.auditStatus == 1) {
        saveAuditRegisterBase(this.auditForm).then((response) => {
          this.$modal.msgSuccess("审批完成");
          this.initData();
          this.auditShow = false;
        });
      } else {
        this.$refs["auditForm"].validate((valid) => {
          if (valid && this.auditForm.remark) {
            saveAuditRegisterBase(this.auditForm).then((response) => {
              this.$modal.msgSuccess("审批完成");
              this.initData();
              this.auditShow = false;
            });
          } else {
            if (!this.auditForm.remark) {
              this.$modal.msgError(`请填写审批意见`);
            } else {
              this.$modal.msgError("请完善表单内容");
            }
          }
        });
      }
    },
    async getRegisterNeed(id, name) {
      try {
        let response = await getRegisterNeed(id);
        let durationMoneyList = response.data.durationMoneyList.split(",");
        let durationNameList = response.data.durationNameList.split(",");
        let durationNameLists = durationNameList.map((item, index) => {
          return {
            name: item,
            money: durationMoneyList[index],
          };
        });
        const target = durationNameLists.find((item) => item.name === name);
        return target ? target.money : 0;
      } catch (error) {
        console.error("getRegisterNeed error:", error);
        return 0;
      }
    },
    // 批量通知
    async noticeOpen() {
      let list = this.dataList.filter((e) => this.ids.indexOf(e.id) > -1);

      // Check if list is empty before accessing list[0]
      if (!list || list.length === 0) {
        this.$modal.msgError("请至少选择一个学员");
        return;
      }

      let durationName = list[0].durationName;
      console.log(durationName);
      let money = await this.getRegisterNeed(
        list[0].registerNeedId,
        durationName
      );
      let materialMoney = list[0]?.registerNoticeVo?.materialMoney ?? 0;
      console.log(list[0]?.registerNoticeVo);
      let registerDeptId = list[0].registerDeptId;
      let originalStartDate = list[0].durationStartDate; // Get original start date
      let originalEndDate = list[0].durationEndDate; // Get original end date
      let formattedStartDate = originalStartDate; // Initialize with original value
      let formattedEndDate = originalEndDate; // Initialize with original value

      // --- Handle Start Date ---
      // Check if originalStartDate is in 'yyyy/MM' format and format as first day
      if (originalStartDate && originalStartDate.split("/").length === 2) {
        const parts = originalStartDate.split("/");
        const year = parseInt(parts[0], 10);
        const month = parseInt(parts[1], 10); // Month is 1-based here
        const formattedMonth = String(month).padStart(2, "0"); // Ensure MM format
        formattedStartDate = `${year}/${formattedMonth}/01`; // Assume first day
      }
      // Optional: Add validation/handling if originalStartDate is already yyyy/MM/dd or other formats

      // --- Handle End Date ---
      // Check if originalEndDate is in 'yyyy/MM' format and calculate the last day
      if (originalEndDate && originalEndDate.split("/").length === 2) {
        const parts = originalEndDate.split("/");
        const year = parseInt(parts[0], 10);
        const month = parseInt(parts[1], 10); // Month is 1-based here

        // Create date for the first day of the *next* month
        const date = new Date(year, month, 1); // JS month is 0-based, so 'month' works directly for next month
        // Set day to 0 to get the last day of the *previous* month (which is the target month)
        date.setDate(0);

        // Format the date as yyyy/MM/dd
        const lastDay = date.getDate();
        const formattedMonth = String(month).padStart(2, "0"); // Ensure MM format
        const formattedDay = String(lastDay).padStart(2, "0"); // Ensure dd format
        formattedEndDate = `${year}/${formattedMonth}/${formattedDay}`;
      }
      // Optional: Add validation/handling if originalEndDate is already yyyy/MM/dd or other formats

      console.log("ooo original start", originalStartDate);
      console.log("ooo formatted start", formattedStartDate);
      console.log("ooo original end", originalEndDate);
      console.log("ooo formatted end", formattedEndDate);

      for (let i = 1; i < list.length; i++) {
        if (
          list[i].durationName != durationName ||
          list[i].registerDeptId != registerDeptId
        ) {
          this.$modal.msgError("请选择进修时长和进修科目都相同的学员");
          return;
        }
      }
      for (let i = 0; i < list.length; i++) {
        console.log(list[i].auditStatus);
        if (list[i].auditStatus !== 3) {
          this.$modal.msgError("只有审批通过的学员才能发送通知");
          return;
        }
      }
      // 检查是否确认报到
      const isSureStatus = await this.checkSureStatus(
        list.map((item) => item.id)
      );
      if (!isSureStatus) {
        return;
      }

      getSureInfo(1)
        .then((res) => {
          this.noticeForm = res.data || {}; // Ensure noticeForm is an object even if res.data is null/undefined
          // Use $set for properties potentially not present initially or to ensure reactivity
          this.$set(this.noticeForm, "engageMoney", money);
          this.$set(this.noticeForm, "registerDate", "");
          console.log("noticeForm engageMoney", materialMoney);
          // 不允许为负数
          this.$set(
            this.noticeForm,
            "materialMoney",
            materialMoney < 0 ? 0 : materialMoney
          );
          console.log("noticeForm engageMoney", this.noticeForm.engageMoney);
          console.log(
            "noticeForm materialMoney",
            this.noticeForm.materialMoney
          );
          // *** CHANGE HERE: Set formattedStartDate and formattedEndDate ***
          this.$set(this.noticeForm, "startDate", formattedStartDate); // Use the formatted start date
          this.$set(this.noticeForm, "endDate", formattedEndDate); // Use the formatted end date

          if (this.noticeForm && this.noticeForm.registerTime) {
            // Check if noticeForm and registerTime exist
            let split = this.noticeForm.registerTime.split("至");
            if (split.length === 2) {
              // Ensure split resulted in two parts
              this.$set(this.noticeForm, "registerTimeStart", split[0]);
              this.$set(this.noticeForm, "registerTimeEnd", split[1]);
            } else {
              // Handle cases where registerTime might not be in the expected format
              this.$set(this.noticeForm, "registerTimeStart", null);
              this.$set(this.noticeForm, "registerTimeEnd", null);
              console.warn(
                "registerTime format is unexpected:",
                this.noticeForm.registerTime
              );
            }
          } else {
            // Initialize time parts if registerTime is missing
            this.$set(this.noticeForm, "registerTimeStart", null);
            this.$set(this.noticeForm, "registerTimeEnd", null);
          }
          // Ensure other potentially missing properties are initialized if needed
          // Example:
          // if (!this.noticeForm.hasOwnProperty('registerDate')) {
          //   this.$set(this.noticeForm, 'registerDate', null);
          // }
          // ... add checks for other properties as necessary ...
        })
        .catch((error) => {
          console.error("Failed to get sure info:", error);
          this.$modal.msgError("获取通知信息失败");
          // Initialize noticeForm to prevent errors if API fails
          this.noticeForm = {
            engageMoney: money,
            startDate: formattedStartDate, // Use the formatted start date
            endDate: formattedEndDate, // Use the formatted end date
            registerTimeStart: null,
            registerTimeEnd: null,
            // Initialize other fields as needed
          };
        });
      this.noticeShow = true;
    },
    registerTimeChange() {
      if (
        this.noticeForm.registerTimeStart &&
        this.noticeForm.registerTimeEnd
      ) {
        this.noticeForm.registerTime =
          this.noticeForm.registerTimeStart +
          "至" +
          this.noticeForm.registerTimeEnd;
      }
    },
    noticeFormSubmit() {
      this.$refs["noticeForm"].validate((valid) => {
        this.noticeForm.startDate = this.noticeForm.startDate
          .replace(/-/g, "/")
          .replace(/T/g, " ");
        this.noticeForm.endDate = this.noticeForm.endDate
          .replace(/-/g, "/")
          .replace(/T/g, " ");

        if (valid) {
          this.noticeForm.registerIdList = this.ids;
          updateSureInfo(this.noticeForm).then((res) => {
            saveNoticeRegisterBase(this.noticeForm).then((response) => {
              this.$modal.msgSuccess("发送成功");
              this.initData();
              this.noticeShow = false;
            });
          });
        } else {
          this.$modal.msgError("请完善表单内容");
        }
      });
    },
    /**
     * 预览通知书内容。
     *
     * 找到选中的第一条数据，复制一份，并将通知书内容赋值给复制的数据。
     * 然后通过接口获取通知书内容，并将内容赋值给复制的数据。
     * 最后，打开预览通知书弹窗，并将复制的数据传递给弹窗。
     *
     * @return {void}
     */
    bookPreviewOpen() {
      let first = this.dataList.find((e) => this.ids.indexOf(e.id) > -1);
      let form = Object.assign(first, {});
      form.registerNoticeVo = this.noticeForm;
      this.bookPreviewForm = form;
      this.bookPreviewShow = true;
      // getSureInfo(1).then((res) => {
      //   form.registerNoticeVo.noticeContent = res.data.noticeContent;
      //   this.bookPreviewForm = form;
      //   this.bookPreviewShow = true;
      // });
    },
    // 批量删除
    handleDelete() {
      const ids = this.ids;
      this.$modal
        .confirm('是否确认删除报名信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delRegisterInfo(ids);
        })
        .then(() => {
          this.initData();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 设置生源类型
    sourceOpen() {
      this.sourceUnitType = consts.sourceUnitTypeList[0].name;
      this.sourceShow = true;
    },
    sourceFormSubmit() {
      let params = {
        registerIdList: this.ids,
        sourceUnitType: this.sourceUnitType,
      };
      saveSourceRegisterBase(params).then((response) => {
        this.$modal.msgSuccess("设置成功");
        this.initData();
        this.sourceShow = false;
      });
    },
    // 修改通知状态
    updateNoticeOpen() {
      this.updateNoticeShow = true;
    },
    /**
     * 修改通知状态表单提交函数。
     *
     * @return {void}
     */
    updateNoticeFormSubmit() {
      let params = {
        registerIdList: this.ids,
        noticeStatus: this.updateNoticeValue,
        // 待报到
        sureStatus: null,
      };
      if (this.updateNoticeValue == 3) {
        params.sureStatus = 1;
      }
      updateNoticeRegisterBase(params).then((response) => {
        this.$modal.msgSuccess("修改成功");
        this.initData();
        this.updateNoticeShow = false;
      });
    },
    // 导出学员
    downloadSignature() {
      let queryParams = { ...this.queryParams }; // 创建一个副本，避免修改原始对象
      delete queryParams.pageSize;
      delete queryParams.pageNum;
      this.download(
        "business/registerInfo/exportSignFile",
        {
          ...queryParams,
        },
        `文件${new Date().getTime()}.zip`
      );
    },
    // 导出学员
    exportStudent() {
      let queryParams = { ...this.queryParams }; // 创建一个副本，避免修改原始对象
      delete queryParams.pageSize;
      delete queryParams.pageNum;
      this.download(
        "business/registerInfo/export",
        {
          ...queryParams,
        },
        `导出学员_${new Date().getTime()}.xlsx`
      );
    },
    // 导出工牌
    exportBadge() {
      this.download(
        "business/registerBase/exportFilterBadge",
        {
          ...this.queryParams,
        },
        `导出工牌_${new Date().getTime()}.zip`
      );
    },
    // 修改通知书内容
    noticeContentOpen() {
      getSureInfo(1).then((res) => {
        this.noticeContentForm = res.data;
        let split = res.data.registerTime.split("至");
        this.$set(this.noticeContentForm, "registerTimeStart", split[0]);
        this.$set(this.noticeContentForm, "registerTimeEnd", split[1]);
        this.noticeContentShow = true;
      });
    },
    openNoticeContent(form) {
      this.bookPreviewFormEdit.registerNoticeVo = form;
      this.bookPreviewEditShow = true;
    },
    saveNoticeContent() {
      this.noticeContentForm.registerTime =
        this.noticeContentForm.registerTimeStart +
        "至" +
        this.noticeContentForm.registerTimeEnd;
      // startDate 和 endDate 日期格式为 "yyyy/MM/dd" 帮我格式化为 "yyyy/MM/dd"
      this.noticeContentForm.startDate = this.noticeContentForm.startDate
        .replace(/-/g, "/")
        .replace(/T/g, " ");
      this.noticeContentForm.endDate = this.noticeContentForm.endDate
        .replace(/-/g, "/")
        .replace(/T/g, " ");
      updateSureInfo(this.noticeContentForm).then((res) => {
        this.$message.success("修改成功");
        this.noticeContentShow = false;
      });
    },
    // 查看名单
    viewOpen(row) {
      this.showType = 2;
      this.queryParams.registerDeptId = row.registerDeptId;
      this.handleQuery();
    },
    //根据期限获取批次
    getDuration(value) {
      if (value) {
        return parseInt(value.split("/")[0], 10);
      }
    },
    // 申报材料
    detailOpen(row) {
      this.registerInfo.id = row.id;
      this.detailShow = true;
    },
    handleQueryEdit(row) {
      console.log(this.editForm);
      const dept = this.registerDeptList.find((item) => item.id === row);
      console.log(dept);
      this.editForm.registerDeptId = dept.id;
      this.editForm.registerDeptName = dept.registerDeptName;
      console.log(this.editForm);
    },
    // 调用接口检查学员是否确认报道
    async checkSureStatus(ids) {
      try {
        const res = await checkSureStatus({ registerIdList: ids });
        console.log(res);
        // 根据接口返回判断学员是否已确认报到
        // 如果 code 为 200 且有确认报到的数据，返回 true
        return res.code === 200;
      } catch (err) {
        console.log(err);
        return false;
      }
    },
    //修改进修科目
    async editF(row) {
      console.log(row);
      // if (row.registerNoticeVo != null) {
      //   this.$message.error("通知书已发，无法修改科室");
      //   return;
      // }
      const isSureStatus = await this.checkSureStatus([row.id]);
      if (!isSureStatus) {
        this.$message.error("该学员已确认来院报到，不支持更改科室");
        return;
      }
      this.editForm = row;
      this.editShow = true;
    },
    editFormSubmit() {
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          updateRegisterInfo(this.editForm).then((response) => {
            this.$message.success("修改成功");
            this.editShow = false;
            this.initData();
          });
        } else {
          this.$modal.msgError("请完善表单内容");
        }
      });
    },
    // 审批历史
    auditLogOpen(row) {
      this.registerInfo.id = row.id;
      this.auditLogShow = true;
    },
    // 通知书
    bookOpen(row, type) {
      this.registerInfo.id = row.id;
      this.bookShow = true;
    },
    // 导入学员信息
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入学员信息";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      window.open(
        this.baseURL + "/business/registerBase/importRegisterTemplate"
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 代理报名
    handleAgent() {
      this.$router.push({
        path: "/business/registerBase/audit/components/registerInfoUpdateNginx",
      });
    },
    //批量签字
    handsign() {
      if (this.isSigning) {
        this.$modal.msgWarning("正在处理中，请稍候...");
        return;
      }
      this.isSigning = true;
      let list = this.dataList.filter((e) => this.ids.indexOf(e.id) > -1);
      for (let i = 0; i < list.length; i++) {
        if (list[i].signCount != 2) {
          this.isSigning = false; // Reset flag if validation fails
          this.$modal.msgError("请选择告知书/承诺书已签署的学员");
          return;
        }
      }
      this.getCodeSign();
      // Add a timeout fallback in case other reset points fail
      setTimeout(() => {
        // Only reset if it's still true (might have been reset by success/error/close)
        if (this.isSigning) {
          this.isSigning = false;
        }
      }, 10000); // Reset after 10 seconds as a safeguard
    },
    // 获取预设签名
    // sign是预设签名和签名二维码
    getCodeSign() {
      if (this.ws) {
        this.ws.close();
        this.ws = null;
      }

      if (this.zt == "ys" || this.mySignQR == "") {
        this.webTargetUrl = `${window.location.origin}/engage-web/sign?type=sign&userId=${this.$store.getters.userId}&zt=ys`;
      } else {
        this.webTargetUrl = `${window.location.origin}/engage-web/sign?type=sign&userId=${this.$store.getters.userId}`;
      }
      this.mySignQR = ""; // Reset previous QR code
      this.signImg = ""; // Reset QR image

      if (!this.signShow) {
        // Only show dialog if it's not already open
        this.signShow = true; // Show dialog immediately
      }
      // Define the function to fetch QR code

      // Call immediately
      this.fetchQRCode();
    },
    fetchQRCode() {
      getKSBatchQRCode({
        registerIdList: this.ids,
        webTargetUrl: this.webTargetUrl,
      })
        .then((res) => {
          this.signImg = res.data.qrCodeImage;
          this.expireUuid = res.data.expireUuid;
          if (res.data.mySignQR && this.zt != "ys") {
            this.mySignQR = res.data.mySignQR;
            this.createWs(this.expireUuid, "expireUuid");
          } else {
            this.showSignImg = true;
            this.createWs(this.$store.getters.userId, "userId");
          }
          this.zt = "";
        })
        .catch((error) => {
          console.error("Error getting QR code:", error);
          this.$modal.msgError("获取签名二维码失败，请重试");
          this.isSigning = false; // Reset flag on error
          this.signShow = false; // Close dialog on error
        });
    },
    createWs(id, type) {
      console.log(type == "userId");
      if (!this.ws) {
        const protocol = this.baseURL.startsWith("https") ? "wss" : "ws";
        let url =
          type == "userId" ? "/websocket/userSign/" : "/websocket/sign/";
        this.ws = new WebSocket(
          protocol + this.baseURL.slice(this.baseURL.indexOf(":")) + url + id
        );
        this.ws.onmessage = (event) => {
          console.log(event.data);
          if (event.data) {
            this.ws.close();
            this.fetchQRCode();
            // WebSocket 收到消息后，不再重新获取签名二维码，避免弹框重复弹出
            // 根据实际业务需求，这里可能需要更新UI状态或执行其他操作
            // 例如：this.signShowT = true; this.signShow = false;
          }
        };
        this.ws.onclose = () => {
          console.log("连接关闭");
        };
      }
    },
    signSubmit() {
      addKXBatchSign({
        userName: this.$store.getters.name,
        registerIdList: this.ids,
        userSignImg: this.mySignQR,
        expireUuid: this.expireUuid,
      }).then((res) => {
        this.$modal.msgSuccess("签字确认成功");
        this.signShow = false;
        this.isSigning = false;
        this.getList();
        this.getCount();
      });
    },
    closeSignDialog() {
      this.signShow = false;
      this.isSigning = false; // Reset flag when dialog is closed/cancelled
      if (this.signIntervalId) {
        clearInterval(this.signIntervalId); // Stop polling if dialog is closed
        this.signIntervalId = null;
      }
    },
    // 处理编辑签名
    handleEditSign() {
      console.log(1212);
      this.showSignImg = true;
      this.mySignQR = "";
      this.zt = "ys";
      this.getCodeSign();
    },

    // 切换视图
    showTypeChange() {
      this.canselAllcheck();
      this.dataList = [];
      this.ids = [];
      this.single = true;
      this.multiple = true;
      this.queryParams.registerDeptId = null;
      this.queryParams.userName = null;
      this.queryParams.auditStatus = null;
      this.queryParams.noticeStatus = null;
      this.tagIndex = 1;

      if (this.isSystem) {
        this.clickAll(3, 2);
      } else {
        this.clickAll(1, 1);
      }
      this.getCount();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.canselAllcheck();

      this.queryParams.pageNum = 1;
      this.initData();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.canselAllcheck();

      this.resetForm("queryForm");
      this.handleQuery();
    },
    //取消全选
    canselAllcheck() {
      this.AllCheck = false;
      this.ids = [];
      this.single = true;
      this.multiple = true;
      this.queryParams.auditStatus = null;
      this.queryParams.noticeStatus = null;
      this.queryParams.signStatus = null;
      this.queryParams.studentNoSign = null;
      this.queryParams.payStatus = null;

      this.tagIndex = 0;
    },
    // 全选
    handleSelectionChangeAll(checked) {
      let ids = [];
      for (let i = 0; i < this.dataList.length; i++) {
        // 使用 $set 确保属性被响应式地修改
        this.$set(this.dataList, i, { ...this.dataList[i], check: checked });
        if (checked) {
          ids.push(this.dataList[i].id);
        }
      }
      this.ids = ids;
      this.single = ids.length !== 1;
      this.multiple = !ids.length;
      console.log(this.multiple);
      console.log(this.single);
    },
    // 多选框选中数据
    handleSelectionChange(checked, index) {
      console.log(checked, index);
      // 使用 $set 确保属性被响应式地修改
      this.$set(this.dataList, index, {
        ...this.dataList[index],
        check: checked,
      });

      let ids = [];
      for (let i = 0; i < this.dataList.length; i++) {
        if (this.dataList[i].check) {
          ids.push(this.dataList[i].id);
        }
      }
      this.ids = ids;
      this.single = ids.length !== 1;
      this.multiple = !ids.length;
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 0 20px 20px 20px;
}

.flex-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  /* 控制列之间的间距 */
  background: #eeeff4;
  padding: 20px 20px;
}

.flex-item {
  min-width: 100px;
  /* 设置最小宽度 */
  text-align: left;
  cursor: pointer;
}

/**
 * 状态容器样式 - 支持自动换行的弹性布局
 */
.status-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  background: #eeeff4;
  padding: 20px;
  border-radius: 4px;
}

/**
 * 状态项样式 - 自适应宽度
 */
.status-item {
  flex: 0 0 auto;
  min-width: 115px;
  max-width: 190px;
  text-align: left;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.3s ease;
  white-space: nowrap;

  // &:hover {
  //   background-color: #f5f7fa;
  //   border-color: #c0c4cc;
  //   transform: translateY(-2px);
  //   box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  // }

  // &:active {
  //   transform: translateY(0);
  // }
}

.enter-container {
  font-family: "Microsoft YaHei";
  font-size: 18px;
  padding: 0 15px;
  line-height: 30px;

  ::v-deep .ql-align-center {
    text-align: center;
  }
}

.border {
  border: 1px solid rgb(153 153 153 / 15%);
  padding: 10px;
  height: 100%;
  display: flex;
  flex-direction: column;
  font-size: 12px;

  // justify-content: center;
  .desc {
    margin-bottom: 10px;
    font-size: 12px;
  }
}

.user-name {
  display: flex;
  align-items: center;
}

.box-container {
  padding: 0;
  padding-left: 20px;
}

::v-deep .el-radio-button__orig-radio + .el-radio-button__inner {
  width: 140px;
}

::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  width: 140px;
}

.custom-select .el-input__inner::placeholder {
  color: red;
  /* 将 placeholder 颜色设置为红色 */
  opacity: 1;
  /* 确保颜色完全显示 */
}

::v-deep .el-input .el-input__inner::placeholder {
  color: #8f8d8d;
  /* 将 placeholder 颜色设置为蓝色 */
  opacity: 1;
  /* 确保颜色完全显示 */
}

.namekey {
  color: #a52529 !important;
}

.custom-table {
  .custom-dept {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid #d8d8d8;
    padding: 0 20px;
    height: 90px;
    margin-bottom: 20px;
    text-align: center;
    font-size: 18px;
    font-weight: bold;

    .desc {
      font-size: 12px;
      color: #999;
      margin-top: 10px;
      font-weight: normal;
    }
  }

  .title {
    font-size: 18px;
    text-align: left;
    color: #000;
  }

  .func {
    font-size: 18px;
    color: #a52529;
    cursor: pointer;
  }

  .custom-dept:hover {
    border: 1px solid red;
  }

  .custom-register-detail {
    margin-top: -10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid rgb(232, 232, 232);
    border-top: none;
    // padding: 10px;
    // text-align: center;
    font-size: 14px;
    max-height: 300px;

    .main-container-detail {
      width: 100%;
      height: 100%;
      background-color: #fff;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      position: relative;
    }

    .download-all {
      position: absolute;
      right: 20px;
      top: 50%;
      transform: translateY(-50%);
      cursor: pointer;
    }

    .header-titles {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 10px;
    }

    .header-titles .el-button {
      margin: 5px;
      font-size: 16px;
      font-weight: bold;
      color: #303133;
      border: none;
      background: transparent;
      padding: 10px;
      cursor: pointer;
      transition: all 0.3s ease;
    }

    .header-titles .el-button.active,
    .header-titles .el-button:hover {
      color: #a52529;
      background-color: #ecf5ff;
    }

    .image-box {
      padding: 15px;
      min-height: 100px;
    }

    .image-box:not(:last-child) {
      border-bottom: 1px solid #e4e7ed;
    }

    .image-with-download {
      position: relative;
      display: inline-block;
      margin: 5px;
    }

    .image-container {
      width: 100px;
      height: 100px;
      object-fit: cover;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.3s ease;
    }

    .image-container:hover {
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      transform: scale(1.05);
    }

    .download-button {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      text-align: center;
      padding: 5px;
      background-color: rgba(0, 0, 0, 0.5);
      color: #fff;
      opacity: 0;
      transition: opacity 0.3s;
    }

    .image-with-download:hover .download-button {
      opacity: 1;
    }
  }

  .custom-register {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid rgb(232, 232, 232);
    // padding: 10px;
    // text-align: center;
    font-size: 14px;
    margin-bottom: 10px;
    height: 150px;

    .info {
      display: flex;
      justify-content: space-between;
      color: #606266;
      font-size: 14px;
      margin-top: 10px;
      .flexInfo {
        display: flex;
        flex-direction: column;
        margin-top: 10px;
        font-size: 14px;
        line-height: 20px;
      }

      .flexInfo:first-child {
        flex: 4;
      }

      .flexInfo:last-child {
        flex: 3;
      }
    }

    .col {
      .desc {
        color: #666666;
        margin-top: 10px;
        font-weight: normal;
      }
    }

    .col:nth-child(1) {
      width: calc(100% - 500px);
      text-align: left;
    }

    .col:nth-child(2) {
      width: 140px;
    }

    .col:nth-child(3) {
      width: 140px;
    }

    .col:nth-child(4) {
      width: 140px;
    }

    .col:nth-child(5) {
      width: 140px;
    }
  }
}
.is-active1 {
  color: #ffffff !important;
  background-color: #5daf34 !important;
}
.is-active2 {
  color: #ffffff !important;
  background-color: #e6a23c !important;
}
.is-active3 {
  color: #ffffff !important;
  background-color: #f56c6c !important;
}

// 支付状态样式
.payment-status {
  &.paid {
    color: #67c23a;
  }
  &.failed {
    color: #f56c6c;
  }
  &.closed,
  &.refunding,
  &.refunded {
    color: #909399;
  }
  &.unknown {
    color: #e6a23c;
  }
  &.default {
    color: #606266;
  }
}
</style>
